package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	private final static String localhost = "localhost";
	private final static String connected = "Connected to localhost in port 2004";
	private final static String serv = "server>";
	private final static String client = "client>";
	private final static String bye = "bye";
	private final static String askQuery = "Write your query";
	private final static String hi = "Hi my server";
	private final static String format = "data received in unknown format";
	private final static String err = "You are trying to connect to an unknown host!";

	void run() {
		try {
			requestSocket = new Socket(localhost, 2004);
			System.out.println(connected);
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			do {
				try {
					message = (String) in.readObject();
					System.out.println(serv + message);
					sendMessage(hi);
					message = (String) in.readObject();
					System.out.println(serv + message);

					System.out.println(askQuery);

					Scanner scanner = new Scanner(System.in);
					sendMessage(scanner.nextLine());

					message = (String) in.readObject();
					System.out.println(serv + message);

					message = bye;
					sendMessage(message);
				} catch (ClassNotFoundException classNot) {
					System.err.println(format);
				}
			} while (!message.equals(bye));
		} catch (UnknownHostException unknownHost) {
			System.err.println(err);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println(client + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}

}
